#include "blockqueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <ctime>

pthread_mutex_t _mutexC = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t _mutexP = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t _condC = PTHREAD_COND_INITIALIZER;
pthread_cond_t _condP = PTHREAD_COND_INITIALIZER;
// 消费
void *Consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 消费
        Task data = bq->pop();

        // 计算
        // data.run();
        data();

        pthread_mutex_lock(&_mutexC);
        pthread_cond_wait(&_condC, &_mutexC);
        std::cout << "处理任务: " << data.GetTask()
                  << " 运算结果是: " << data.GetResult()
                  << " thread id: " << pthread_self()
                  << std::endl;
        pthread_cond_signal(&_condP);
        pthread_mutex_unlock(&_mutexC);
    }
}
// 生产
void *Productor(void *args)
{
    int len = opers.size();
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    int data = 0;
    while (true)
    {
        // 模拟生产者生产数据
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10 + 1;
        char op = opers[rand() % len];
        Task data(data1, data2, op);

        // 生产
        bq->push(data);
        pthread_mutex_lock(&_mutexP);
        std::cout << "生产了一个任务: " << data.GetTask() 
                  << " thread id: " << pthread_self() 
                  << std::endl;
        pthread_cond_signal(&_condC);
        pthread_mutex_unlock(&_mutexP);
        sleep(1);
    }
}
int main()
{
    srand(time(nullptr));
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    // 多生产多消费
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, Consumer, bq);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, Productor, bq);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete bq;
    return 0;
}